/// Dart import
import 'dart:math' as math;

/// Package imports
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:palmf_hid/common/entities/data_base/my_database.dart';

// ignore: depend_on_referenced_packages
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

/// Set order's data collection to data grid source.
class PetInfoDataGridSource extends DataGridSource {
  /// Creates the order data source class with required details.
  PetInfoDataGridSource(
      {this.orderDataCount,
      this.ordersCollection,
      this.culture,
      bool? isFilteringSample,
      bool isGrouping = false}) {
    this.isFilteringSample = isFilteringSample ?? false;
    orders = ordersCollection ?? _fetchOrders(orders, orderDataCount ?? 100);
    currencySymbol = _obtainCurrencySymbol();
    buildDataGridRows(isGrouping);
  }

  /// Localization Source.
  String? culture;
  /// Get data count of an order.
  int? orderDataCount;
  final math.Random _random = math.Random();

  /// Instance of an order.
  List<PetInfo> orders = <PetInfo>[];

  /// Instance of an order collection for rtl sample
  List<PetInfo>? ordersCollection;

  /// Instance of DataGridRow.
  List<DataGridRow> dataGridRows = <DataGridRow>[];

  /// Currency symbol for culture.
  String currencySymbol = '';

  /// Checks whether the source is used for the filtering sample or not.
  late bool isFilteringSample;

  /// Building DataGridRows.
  void buildDataGridRows(bool isGrouping) {
    dataGridRows = orders.map<DataGridRow>((PetInfo order) {
      {
        return DataGridRow(cells: <DataGridCell>[
          DataGridCell<int>(
              columnName: _fetchColumnName('ID'), value: order.id),
          DataGridCell<int>(
              columnName: _fetchColumnName('CustomerId'), value: order.id),
          DataGridCell<String>(
              columnName: _fetchColumnName('Name'), value: order.petName),
          DataGridCell<String>(
              columnName: _fetchColumnName('Freight'), value: order.masterName),
          DataGridCell<String>(
              columnName: _fetchColumnName('City'), value: order.phone),
          DataGridCell<String>(
              columnName: _fetchColumnName('Price'), value: order.petSex),
        ]);
      }
    }).toList();
  }

  // Overrides

  @override
  List<DataGridRow> get rows => dataGridRows;

  @override
  DataGridRowAdapter buildRow(DataGridRow row) {
    Color backgroundColor = Colors.transparent;
    return DataGridRowAdapter(color: backgroundColor, cells: <Widget>[
      Container(
        padding: const EdgeInsets.all(8),
        alignment: Alignment.centerRight,
        child: Text(
          row.getCells()[0].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        padding: const EdgeInsets.all(8),
        alignment: Alignment.centerRight,
        child: Text(
          row.getCells()[1].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        padding: const EdgeInsets.all(8),
        alignment: Alignment.centerLeft,
        child: Text(
          row.getCells()[2].value.toString(),
        ),
      ),
      Container(
        padding: const EdgeInsets.all(8),
        alignment: Alignment.centerRight,
        child: Text(
            NumberFormat.currency(locale: 'en_US', symbol: currencySymbol)
                .format(row.getCells()[3].value)),
      ),
      Container(
        padding: const EdgeInsets.all(8),
        alignment: Alignment.centerLeft,
        child: Text(
          row.getCells()[4].value.toString(),
          overflow: TextOverflow.ellipsis,
        ),
      ),
      Container(
        padding: const EdgeInsets.all(8),
        alignment: Alignment.centerRight,
        child: Text(NumberFormat.currency(
                locale: 'en_US', symbol: currencySymbol, decimalDigits: 0)
            .format(row.getCells()[5].value)),
      ),
    ]);
  }

  /// Currency symbol
  String _obtainCurrencySymbol() {
    final format = NumberFormat.simpleCurrency();
    return format.currencySymbol;
  }

  @override
  Future<void> handleLoadMoreRows() async {
    await Future<void>.delayed(const Duration(seconds: 5));
    orders = _fetchOrders(orders, 15);
    buildDataGridRows(false);
    notifyListeners();
  }

  @override
  Future<void> handleRefresh() async {
    await Future<void>.delayed(const Duration(seconds: 5));
    orders = _fetchOrders(orders, 15);
    buildDataGridRows(false);
    notifyListeners();
  }

  @override
  Widget? buildTableSummaryCellWidget(
      GridTableSummaryRow summaryRow,
      GridSummaryColumn? summaryColumn,
      RowColumnIndex rowColumnIndex,
      String summaryValue) {
    Widget? widget;
    Widget buildCell(String value, EdgeInsets padding, Alignment alignment) {
      return Container(
        padding: padding,
        alignment: alignment,
        child: Text(value,
            overflow: TextOverflow.ellipsis,
            style: const TextStyle(fontWeight: FontWeight.w500)),
      );
    }

    if (summaryRow.showSummaryInRow) {
      widget = buildCell(
          summaryValue, const EdgeInsets.all(16.0), Alignment.centerLeft);
    } else if (summaryValue.isNotEmpty) {
      if (summaryColumn!.columnName == 'freight') {
        summaryValue = double.parse(summaryValue).toStringAsFixed(2);
      }

      summaryValue = 'Sum: ' +
          NumberFormat.currency(locale: 'en_US', decimalDigits: 0, symbol: r'$')
              .format(double.parse(summaryValue));

      widget = buildCell(
          summaryValue, const EdgeInsets.all(8.0), Alignment.centerRight);
    }
    return widget;
  }

  @override
  Widget? buildGroupCaptionCellWidget(
      RowColumnIndex rowColumnIndex, String summaryValue) {
    return Container(
        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 15),
        child: Text(summaryValue));
  }

  /// Provides the column name.
  String _fetchColumnName(String columnName) {
    if (isFilteringSample) {
      switch (columnName) {
        case 'id':
          return 'Order ID';
        case 'customerId':
          return 'Customer ID';
        case 'name':
          return 'Name';
        case 'freight':
          return 'Freight';
        case 'city':
          return 'City';
        case 'price':
          return 'Price';
        default:
          return columnName;
      }
    }
    return columnName;
  }

  /// Update DataSource
  void updateDataSource() {
    notifyListeners();
  }

  final List<String> _chineseNames = <String>[
    '克勞利',
    '布隆普',
    '民間',
    '爾灣',
    '佛利格',
    '頂峰',
    '法語',
    '沃思',
    '林諾德',
    '辛普',
    '梅雷普',
    '風險',
    '塞維斯',
    '胡扯',
    '阿里基',
  ];

  final List<String> _chineseCties = <String>[
    '布魯塞爾',
    '羅薩里奧',
    '累西腓',
    '格拉茨',
    '蒙特利爾',
    '薩瓦森',
    '坎皮納斯',
    '重新發送',
  ];

  /// Get orders collection
  List<PetInfo> _fetchOrders(
    List<PetInfo> orderData,
    int count,
  ) {
    final int startIndex = orderData.isNotEmpty ? orderData.length : 0,
        endIndex = startIndex + count;
    List<String> city;
    List<String> names;

    city = _chineseCties;
    names = _chineseNames;

    return orderData;
  }
}
